package com.tanchengjin.admin.modules.blog.controller;

import com.github.pagehelper.PageInfo;
import com.tanchengjin.admin.exception.ApplicationException;
import com.tanchengjin.admin.modules.blog.service.ArticleService;
import com.tanchengjin.admin.modules.cms.pojo.Article;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping("/article")
public class ArticleController {
    @Autowired
    private ArticleService articleService;

    @GetMapping("/{id}")
    public String detail(Model view, @PathVariable(value = "id") long id) {
        Article article = null;
        try {
            article = articleService.findOne(id);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (article == null) {
            throw new ApplicationException("文章不存在");
        }
        view.addAttribute("article", article);
        return "/index/article/detail";
    }

    @GetMapping("/tag/{tag}")
    public String getByTag(Model view, @PathVariable(required = true, value = "tag") String tag, @RequestParam(required = false, defaultValue = "1") Integer page, @RequestParam(required = false, defaultValue = "9") Integer size) {
        PageInfo<Article> articleList = articleService.getArticleListByTag(tag, page, size);
        view.addAttribute("articleList", articleList);
        view.addAttribute("urlValue", "article/tag/" + tag);
        return "index/index";
    }

    @GetMapping("/search")
    public String search(Model view, @RequestParam(required = false, defaultValue = "") String q, @RequestParam(required = false, defaultValue = "1") Integer page, @RequestParam(required = false, defaultValue = "9") Integer size) {
        if (q == null || q.isEmpty()) {
            return "redirect:/";
        }
        PageInfo<Article> articleList = articleService.getArticleListByPaginationWithSearch(page, size, q);
        view.addAttribute("articleList", articleList);
        view.addAttribute("urlValue", "/article/search?q=" + q);
        return "/index/index";
    }

}
